package com.jctrip.hotel.common.util;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/**
 * Bean工具类
 */
public class BeanUtil extends org.springframework.beans.BeanUtils {

    /**
     * Bean属性复制工具方法。
     */
    public static void copyProperties(Object source, Object target, boolean ignoreNull) {
        try {
            if (ignoreNull) {
                copyProperties(source, target, getNullPropertyNames(source));
            } else {
                copyProperties(source, target);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取需要忽略的属性
     *
     * @param dest 目标对象
     * @return 空属性名称列表
     */
    private static String[] getNullPropertyNames(Object dest) {
        final BeanWrapper src = new BeanWrapperImpl(dest);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            // 此处判断可根据需求修改
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
